<template>
  <AdminHeader></AdminHeader>
  <div class="admin-users">
    <div class="search-bar">
        <el-select v-model="searchType" placeholder="请选择搜索类型" class="search-type">
          <el-option label="用户名" value="1"></el-option>
          <el-option label="昵称" value="2"></el-option>
        </el-select>
        <el-input v-model="searchInput" @keydown.enter="search" placeholder="请输入搜索内容" class="search-input"></el-input>
        <el-button type="primary" @click="search">搜索</el-button>
    </div>
    <el-button type="success" @click="addUser()">+ 增加用户</el-button>
    <el-table :data="filteredUsers.length ? filteredUsers : users" stripe style="width: 100%" class="user-table">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="nickname" label="昵称"></el-table-column>
      <el-table-column prop="introduce" label="介绍"></el-table-column>
      <el-table-column prop="isAuthor" label="是否为作者">
        <template #default="scope">
          {{ scope.row.isAuthor ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="editUser(scope.row.username)">编辑</el-button>
          <el-button type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container" v-if="!isSearching">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="totalUsers"
          class="pagination">
      </el-pagination>
    </div>
  </div>
</template>

<script lang="js">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import VueCookies from "vue-cookies";
import AdminHeader from "@/components/AdminHeader.vue";
import {ElMessageBox, ElNotification} from "element-plus";
import router from "@/router/index.js";
import config from "../../../config/config.js";

export default {
  components: {
    AdminHeader,
  },
  setup() {
    const users = ref([]);
    const totalUsers = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(1);
    const searchInput = ref('');
    const searchType = ref('1'); // 默认搜索类型为用户名
    const filteredUsers = ref([]);
    const adminToken = VueCookies.get('adminToken');
    const isSearching = ref(false);

    const fetchUsers = async () => {
      try {
        const response = await axios.get(`${config.apiUrl}/admin/user/all?page=${currentPage.value}`, {
          headers: {
            Authorization: `Bearer ${adminToken}`
          }
        });
        users.value = response.data.users;
        totalUsers.value = response.data.totalPages * pageSize.value;
      } catch (error) {
        console.error('Error fetching users:', error);
      }
    };

    const search = async () => {
      filteredUsers.value = []; // 清空搜索结果
      isSearching.value = true;
      const apiUrl = `${config.apiUrl}/user/search?username=${searchInput.value}&type=${searchType.value}`;
      try {
        const response = await axios.get(apiUrl, {
          headers: {
            Authorization: `Bearer ${adminToken}`
          }
        });
        if (response.data && response.data.length > 0) {
          filteredUsers.value = response.data;
        }else{
          filteredUsers.value = response.data;
          ElNotification({
            message: "没找到："+searchInput.value+" ！",
            type: 'warning',
            duration: 1000
          });
        }
      } catch (error) {
        console.error('Error searching users:', error);
      }
    };


    const handleSizeChange = (val) => {
      pageSize.value = val;
      fetchUsers();
    };

    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fetchUsers();
    };
    const editUser = (user) => {
      // 编辑用户逻辑
      router.push('/admin/edituser/'+user);
    };
    const addUser = () => {
      router.push('/admin/adduser');
    };

    const deleteUser = async (userId) => {
      try {
        // 弹出确认对话框
        await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        // 用户确认删除后执行删除操作
        const apiUrl = `${config.apiUrl}/user/delete?id=${userId}`;
        const response = await axios.get(apiUrl, {
          headers: {
            Authorization: `Bearer ${adminToken}`
          }
        });
        if (response.status === 200){
          ElNotification({
            message: response.data.message,
            type: 'success',
            duration: 1000
          });
        }else{
          ElNotification({
            message: response.data.message,
            type: 'warning',
            duration: 1800
          });
        }

        // 删除成功后更新用户列表数据
        if (searchInput.value) {
          await search();
        } else {
          // 否则，更新用户列表数据
          await fetchUsers();
        }
      } catch (error) {
        console.error('Error delete user:', error);
      }
    };

    onMounted(() => {
      fetchUsers();
    });



    return {
      users,
      totalUsers,
      currentPage,
      pageSize,
      searchInput,
      searchType,
      filteredUsers,
      search,
      handleSizeChange,
      handleCurrentChange,
      editUser,
      deleteUser,
      addUser,
      isSearching,
    };
  },
};
</script>

<style scoped>
.admin-users {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-type {
  width: 100px;
  margin-right: 10px;
}

.search-input {
  width: 80%;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  flex-wrap: wrap; /* 允许弹性项目在需要时换行 */
}
.pagination {
  max-width: 100%; /* 限制宽度为父容器的100% */
  overflow-x: auto; /* 如果内容超出宽度，则显示水平滚动条 */
}

.user-table {
  margin-top: 20px;
}
</style>
